#include "stdafx.h"

Object::Object(HDC hdc, const std::wstring & picname)
{
	image = ImageMgr::getInstance()->getImageFromName(picname);

	BITMAPINFO bmi = { sizeof(bmi),XMAP*GRIDSIZE,YMAP*GRIDSIZE,1,32, };
	memDC = CreateCompatibleDC(hdc);
	HBITMAP bmp = CreateDIBSection(hdc, &bmi, DIB_RGB_COLORS, NULL, NULL, 0);
	SelectObject(memDC, bmp);
	DeleteObject(bmp);
	mg = new Graphics(memDC);
}

Object::~Object()
{
	delete mg;
	DeleteDC(memDC);
}

void Object::draw(Graphics * graphics)
{
	BitBlt(graphics->GetHDC(), LEFTMAP, TOPMAP, XMAP*GRIDSIZE, YMAP*GRIDSIZE, memDC, 0, 0, SRCCOPY);
}

void Object::draw(HDC hdc)
{
	GdiAlphaBlend(hdc, LEFTMAP, TOPMAP, WIDTHMAP, HEIGHTMAP, memDC, 0, 0, WIDTHMAP, HEIGHTMAP, bf);
}

void Object::update()
{
	mg->Clear(0x0);

	for (int i = 0; i < XMAP; i++)
	{
		for (int j = 0; j < YMAP; j++)
		{
			if (c[i][j])
			{
				mg->DrawImage(image, i*GRIDSIZE, j*GRIDSIZE);
			}
		}
	}
}

bool Object::collide(Point pt)
{
	int x = floor((pt.X - LEFTMAP) / (double)GRIDSIZE);
	int y = floor((pt.Y - TOPMAP) / (double)GRIDSIZE);

	if (x >= 0 && x < XMAP && y >= 0 && y <= YMAP)
	{
		return c[x][y];
	}
	else
	{
		return false;
	}
}

void Object::set(int x, int y, bool value)
{
	c[x][y] = value;
}

bool Object::collide(Rect rc)
{
	int x1 = floor((rc.GetLeft() - LEFTMAP) / (double)GRIDSIZE);
	int x2 = floor((rc.GetRight() - LEFTMAP) / (double)GRIDSIZE);
	int y1 = floor((rc.GetTop() - TOPMAP) / (double)GRIDSIZE);
	int y2 = floor((rc.GetBottom() - TOPMAP) / (double)GRIDSIZE);

	if (x1 < 0 && x2 < 0 || x1 >= XMAP && x2 >= XMAP || y1<0 && y2<0 || y1>YMAP && y2>YMAP)
	{
		return false;
	}
	else
	{
		x1 = max(x1, 0);
		x1 = min(x1, XMAP - 1);
		x2 = max(x2, 0);
		x2 = min(x2, XMAP - 1);
		y1 = max(y1, 0);
		y1 = min(y1, YMAP - 1);
		y2 = max(y2, 0);
		y2 = min(y2, YMAP - 1);

		for (int i = x1; i <= x2; i++)
		{
			for (int j = y1; j <= y2; j++)
			{
				if (c[i][j])
				{
					return true;
				}
			}
		}
	}

	return false;
}

Wall::Wall(HDC hdc, const std::wstring & picname) :Object(hdc, picname)
{
	/*for (int i = 1; i < XMAP - 1; i++)
	{
		c[i][1] = true;
	}
	update();*/
}

Wall::~Wall()
{
}

void Wall::crash(std::initializer_list<std::pair<int, int>> list)
{
	for (auto i : list)
	{
		c[i.first][i.second] = false;
	}

	update();
}

Steel::Steel(HDC hdc, const std::wstring & picname) :Object(hdc, picname)
{
	/*for (int i = 0; i < XMAP - 1; i++)
	{
		c[i][0] = true;
		c[XMAP - 1][i] = true;
		c[i + 1][YMAP - 1] = true;
		c[0][i + 1] = true;
	}
	update();*/
}

Steel::~Steel()
{
}

Water::Water(HDC hdc, const std::wstring & picname) :Object(hdc, picname)
{
	/*for (int i = 1; i < XMAP - 1; i++)
	{
		c[i][2] = true;
	}
	update();*/
}

Water::~Water()
{
}

Grass::Grass(HDC hdc, const std::wstring & picname) :Object(hdc, picname)
{
	for (int i = 0; i < XMAP; i++)
	{
		c[i][10] = true;
	}
	update();
}

Grass::~Grass()
{
}